﻿using System;
using System.Collections.ObjectModel;

using Sunyi.Project.WebPoint.DataAccessController;
using Sunyi.Project.WebPoint.DataContract;

namespace Sunyi.Project.WebPoint.BusinessLogic
{
    public partial class UserServiceManager
    {
        UserDaoController controller = new UserDaoController();

        public User GetUser(Guid id)
        {
            return controller.Select(id);
        }

        public User GetUser(string userName)
        {
            return controller.SelectByName(userName);
        }

        public void UpdateUser(User user, Collection<Guid> removedRoles)
        {
            var localUser = controller.SelectByName(user.UserName);

            if (user.Roles != null) RemoveNotExistRoles(user);

            if (localUser == null)
            {
                controller.Insert(user);
            }
            else
            {
                localUser.Password = user.Password;
                localUser.UpdateTimestamp = user.UpdateTimestamp;

                if (removedRoles != null)
                {
                    foreach (var removedRoleId in removedRoles) { if (localUser.Roles.Contains(removedRoleId)) localUser.Roles.Remove(removedRoleId); }
                }

                foreach (var roleId in user.Roles) { if (!localUser.Roles.Contains(roleId)) { localUser.Roles.Add(roleId); } }

                controller.Save(localUser);
            }
        }

        private void RemoveNotExistRoles(User user)
        {
            var removedRoles = new Collection<Guid>();
            var roleDaoController = new RoleDaoController();

            foreach (var roleId in user.Roles) { var role = roleDaoController.Select(roleId); if (role == null) removedRoles.Add(roleId); }

            foreach (var removedRole in removedRoles) { if (user.Roles.Contains(removedRole)) user.Roles.Remove(removedRole); }
        }
    }
}
